﻿using System;
using System.Linq;
using System.Reflection;

namespace Inovout.Descriptors
{
    public abstract class MemberDescriptor
    {
        protected const BindingFlags AllBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;

        public string Name
        {
            get { return memberInfo.Name; }
        }
        public Type DeclaringType { get { return memberInfo.DeclaringType; } }

        public string Alias
        {
            get
            {
                string alias = string.Empty;
                //  string alias = StringResources.GetString(memberInfo, StringResourceType.Alias);
                //if (!string.IsNullOrEmpty(alias))
                //{
                //    return alias;
                //}
                AliasAttribute aliasAttribute;

                if (TryGetAttribute<AliasAttribute>(out aliasAttribute))
                {
                    return aliasAttribute.Name;
                }
                else
                {
                    return memberInfo.Name;
                }
            }
        }
        private Attribute[] attributes;
        private MemberInfo memberInfo;
        public MemberDescriptor(MemberInfo memberInfo)
        {
            this.memberInfo = memberInfo;
            attributes = Attribute.GetCustomAttributes(memberInfo, false);
        }
        public bool HasAttribute<TAttribute>() where TAttribute : Attribute
        {
            return HasAttribute(typeof(TAttribute));
        }
        public bool HasAttribute(Type attributeType)
        {
            return !(GetAttributes(attributeType).Length == 0);
        }

        public bool TryGetAttribute<TAttribute>(out TAttribute attibute) where TAttribute : Attribute
        {
            if (HasAttribute<TAttribute>())
            {
                attibute = GetAttribute<TAttribute>();
                return true;
            }
            else
            {
                attibute = null;
                return false;
            }
        }
        public TAttribute GetAttribute<TAttribute>() where TAttribute : Attribute
        {
            return (TAttribute)GetAttributes(typeof(TAttribute))[0];
        }
        public Attribute[] GetAttributes(Type attributeType)
        {
            Attribute[] customAttributes = attributes.Where((attribute) =>
            {
                return attributeType.IsInstanceOfType(attribute);
            }).ToArray();

            return customAttributes;
        }
        public TAttribute[] GetAttributes<TAttribute>() where TAttribute : Attribute
        {
            return (TAttribute[])GetAttributes(typeof(TAttribute));
        }

    }
}
